package com.beiben.quality.service.impl;

import java.util.Arrays;
import java.util.List;

import com.beiben.system.group.domain.Group;
import com.beiben.system.group.mapper.GroupMapper;
import com.beiben.system.user.domain.BeiBenUser;
import com.beiben.system.user.mapper.BeiBenUserMapper;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;
import com.beiben.quality.mapper.QaQualityInfoMapper;
import com.beiben.quality.domain.QaQualityInfo;
import com.beiben.quality.service.IQaQualityInfoService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 质量信息Service业务层处理
 *
 * @author gx
 * @date 2021-03-08
 */
@Service
public class QaQualityInfoServiceImpl implements IQaQualityInfoService {

    private static final Logger log = LoggerFactory.getLogger(QaQualityInfoServiceImpl.class);

    @Autowired
    private QaQualityInfoMapper qaQualityInfoMapper;

    @Autowired
    private GroupMapper groupMapper;//组别


    /**
     * 查询质量信息
     *
     * @param qualityId 质量信息ID
     * @return 质量信息
     */
    @Override
    public QaQualityInfo selectQaQualityInfoById(Long qualityId) {
        return qaQualityInfoMapper.selectQaQualityInfoById(qualityId);
    }

    /**
     * 查询质量信息列表
     *
     * @param qaQualityInfo 质量信息
     * @return 质量信息
     */
    @Override
    public List<QaQualityInfo> selectQaQualityInfoList(QaQualityInfo qaQualityInfo) {
        return qaQualityInfoMapper.selectQaQualityInfoList(qaQualityInfo);
    }

    /**
     * 新增质量信息
     *
     * @param qaQualityInfo 质量信息
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, timeout = 72000, rollbackFor = Exception.class)
    public int insertQaQualityInfo(QaQualityInfo qaQualityInfo) {
        qaQualityInfo.setCreateTime(DateUtils.getNowDate());
        qaQualityInfo.setCreateBy(SecurityUtils.getUsername());
        qaQualityInfo.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        qaQualityInfo.setDeptName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
        int result = qaQualityInfoMapper.insertQaQualityInfo(qaQualityInfo);
        List<String> infoGroups = qaQualityInfo.getGroupList();
        Long qualityId = qaQualityInfo.getQualityId();
        qaQualityInfoMapper.insertQualityGroups(qualityId, infoGroups);
        return result;

    }

    /**
     * 修改质量信息
     *
     * @param qaQualityInfo 质量信息
     * @return 结果
     */
    @Override
    public int updateQaQualityInfo(QaQualityInfo qaQualityInfo) {
        qaQualityInfo.setUpdateTime(DateUtils.getNowDate());
        qaQualityInfo.setUpdateBy(SecurityUtils.getUsername());
        qaQualityInfo.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        qaQualityInfo.setDeptName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
        int result = qaQualityInfoMapper.updateQaQualityInfo(qaQualityInfo);
        Long qualityId = qaQualityInfo.getQualityId();
        qaQualityInfoMapper.deleteQualityGroupsByQualityId(qualityId);
        List<String> infoGroups = qaQualityInfo.getGroupList();
//        String[] groups = qaQualityInfo.getGroups().replaceAll("，", ",").split(",");
        qaQualityInfoMapper.insertQualityGroups(qualityId, infoGroups);
        return result;
    }

    /**
     * 批量删除质量信息
     *
     * @param qualityIds 需要删除的质量信息ID
     * @return 结果
     */
    @Override
    public int deleteQaQualityInfoByIds(Long[] qualityIds) {
        qaQualityInfoMapper.deleteQualityGroupsByQualityIds(qualityIds);
        return qaQualityInfoMapper.deleteQaQualityInfoByIds(qualityIds);


    }

    /**
     * 删除质量信息信息
     *
     * @param qualityId 质量信息ID
     * @return 结果
     */
    @Override
    public int deleteQaQualityInfoById(Long qualityId) {

        return qaQualityInfoMapper.deleteQaQualityInfoById(qualityId);
    }

    @Override
    public List<String> selectQaQualityInfoByQualityId(Long qualityId) {
        return qaQualityInfoMapper.selectQaQualityInfoByQualityId(qualityId);
    }


    /**
     * 导入新增质量信息
     */

    @Transactional(propagation = Propagation.REQUIRED, timeout = 72000, rollbackFor = Exception.class)
    public int insertQaQualityInfoByImport(QaQualityInfo qaQualityInfo) {
//        qaQualityInfo.setCreateTime(DateUtils.getNowDate());
//        qaQualityInfo.setCreateBy(SecurityUtils.getUsername());
//        qaQualityInfo.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
//        qaQualityInfo.setDeptName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
        int result = qaQualityInfoMapper.insertQaQualityInfo(qaQualityInfo);
        String[] groups = qaQualityInfo.getGroups().replaceAll("，", ",").split(",");
        //String infoGroups = qaQualityInfo.getGroupList();
        Long qualityId = qaQualityInfo.getQualityId();
        qaQualityInfoMapper.insertQualityGroupsByImport(qualityId, groups);
        return result;

    }

    /**
     * 导入质量信息
     *

     */
    @Override
    public String importSampleQuality(List<QaQualityInfo> list, Boolean isUpdateSupport) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (QaQualityInfo qaQualityInfo : list)
        {
            try
            {
                if (null != qaQualityInfo )
                {
                    // TODO: 2021/3/24 组别不能为空，系统，车型不能为空
                    if(StringUtils.isEmpty(qaQualityInfo.getGroups())){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、组别不能为空,数据导入失败：");
                    }else if(StringUtils.isEmpty(qaQualityInfo.getWorkSystem())){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、系统不能为空,数据导入失败：");
                    }else if(StringUtils.isEmpty(qaQualityInfo.getCarType())){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、车型不能为空,数据导入失败：");
                    }else if(StringUtils.isEmpty(qaQualityInfo.getProblemStage())){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、问题发生阶段不能为空,数据导入失败：");
                    }else{
                        boolean isRight = true;
                        if(StringUtils.equals(qaQualityInfo.getProblemStage(),"3")){
                            if(StringUtils.isEmpty(qaQualityInfo.getQuestionClassification())){
                                failureNum++;
                                failureMsg.append("<br/>" + failureNum + "、问题分类不能为空,数据导入失败：");
                                isRight = false;
                            }
                        }
                        if(isRight){
                            boolean isGroup = true;
                            String[] groups = qaQualityInfo.getGroups().replaceAll("，", ",").split(",");
                            for(String group:groups){
                                // TODO: 2021/3/24 按编码查询组别
                                Group gp =  groupMapper.selectGroupByCode(group);
                                if(null==gp){
                                    isGroup = false;
                                    break;
                                }
                            }
                            if(!isGroup){
                                failureNum++;
                                failureMsg.append("<br/>" + failureNum +"组别："+groups[0]+ "系统中不存在,数据导入失败：");
                            }else{
                                this.insertQaQualityInfoByImport(qaQualityInfo);
                                successNum++;
                            }
                        }
                    }
                }

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、项目名称: " + qaQualityInfo.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共: " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共: " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


}
